/**Copyright (c) 2010, Isidoro Trevino de la Garza (chololo@gmail.com)
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:
(1)Redistributions of source code must retain the above copyright notice, this list 
of conditions and the following disclaimer. 
(2)Redistributions in binary form must reproduce the above copyright notice, this 
list of conditions and the following disclaimer in the documentation and/or other 
materials provided with the distribution. 
 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 
DAMAGE.
*/
package org.citsa.generator.html

import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.FileTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration 
import freemarker.template.DefaultObjectWrapper 
import freemarker.template.Template 
import org.apache.maven.jxr.JXR 
import org.citsa.configuration.ConfigurationManager 
import org.citsa.ofbiz.parser.FileComponentRegistry;
import org.apache.maven.jxr.log.Log
class DocumentationGenerator {
	
	def cfg
	
	def initConfiguration(def config){
		cfg = new Configuration();
		//cfg.setClassForTemplateLoading(config.getTemplateDir())
		def folder = config.getTemplateDir()
		def loaders= [] 
		ClassTemplateLoader classLoader = new ClassTemplateLoader(this.getClass(), config.getTemplatePreffix())
		/*if(folder.exists()){
			FileTemplateLoader fileLoader = new FileTemplateLoader(folder)
			loaders << fileLoader
		}*/		
		MultiTemplateLoader multiLoader = new MultiTemplateLoader(loaders as TemplateLoader[])
		cfg.setTemplateLoader(classLoader)
		cfg.setObjectWrapper(new DefaultObjectWrapper())	
	}
	
	def generateDocumentation(def components){
		def template
		
		def config = ConfigurationManager.instance()
		initConfiguration(config)
		
		
		components.each{ component ->
			String type = component.getElementType()
			switch(type){
				case "webapp":
					template = "webapp.ftl"
					break
				case "serviceResource":
					if(component.type=="model"){					
						template = "service.ftl"
					}
					else if(component.type=="group"){					
						template = "group.ftl"
					}
					else if(component.type=="eca"){					
						template = "eca.ftl"
					}
					else{
						template=null
					}
					break
				case "entityResource":
					if(component.type=="model"){
						template = "entity.ftl"
					}
					else{
						template=null
					}
					break
				default:
					template=null
					break
			}
			if(template){
				def dir = generateDirectories(component)
				println "${this.getClass().getResource(config.getTemplatePreffix()+template)}"				
				Template temp = cfg.getTemplate(template);
				def elements= [:]
				elements['components']=components
				elements['component'] = component
				elements['dir'] = config.getSiteRelativeDir(component)
				elements['registry'] = FileComponentRegistry.instance()
				def fileName = "${dir}/${component.name.replace(" ","")}.html"
				Writer out = new BufferedWriter(new FileWriter(new File(fileName)))
				
				temp.process(elements, out);
				out.flush();
			}
		}
		generateSideFiles(components,config)
		
		
	}
	def generateJavaSourceXRef(){
		def config = ConfigurationManager.instance()
		def ant = new AntBuilder()
		ant.taskdef(name:"sorcerer", classname:"org.jvnet.sorcerer.ant.SorcererTask")
		def modules =  config.getModulePaths()
		ant.mkdir(dir:"site/xref")
		/*modules.each{
			module->
			//ant.sorcerer(srcdir:config.generalProperties["ofbiz.base.installation"]+"/",destdir:"site/xref"){
			ant.sorcerer(srcdir:module,destdir:"site/xref"){
				include(name:"***.java")
			}
		}*/
		JXR jxr = new JXR();
		jxr.setDest( "site/jxr" );
		jxr.setLog( [info:{println it},
		debug:{println it},
		warn:{println it},
		error:{println it}] as Log );
		println modules[1]
		jxr.xref( modules, "templates",
		               "WindowsTitle", "DocTitle", "Bottom" );

	}
	
	def generateSideFiles(def components,def config){
		def elements= [:]
		elements['components']=components
		
		Template temp = cfg.getTemplate("components.ftl");
		Writer out = new BufferedWriter(new FileWriter(new File("${config.generalProperties['output.dir']}/components.html")))
		temp.process(elements, out);
		out.flush();
		
		generateEntityIndex(components,config)
		generateWebappIndex(components,config)
		generateServiceIndex(components,config)
		generateModuleIndex(components, config)
	}
	
	def generateWebappIndex(def components,def config){
		def elements= [:]
		def registry = FileComponentRegistry.instance()
		
		elements['components']=components
		elements['registry']=registry
		elements['requests']=registry.alphabeticalRequests()
		elements['screens']=registry.alphabeticalScreens()
		elements['forms']=registry.alphabeticalForms()
		Template temp = cfg.getTemplate("webapp-alphabetical.ftl");
		Writer out = new BufferedWriter(new FileWriter(new File("${config.generalProperties['output.dir']}/webapp-alphabetical.html")))
		temp.process(elements, out);
		out.flush();
		
	}
	def generateServiceIndex(def components,def config){
		def elements= [:]
		def registry = FileComponentRegistry.instance()
		
		elements['components']=components
		elements['registry']=registry
		elements['services']=registry.alphabeticalServices()
		elements['serviceGroups']=registry.alphabeticalServiceGroups()
		elements['serviceEcas']=registry.alphabeticalServiceEcas()
		Template temp = cfg.getTemplate("service-alphabetical.ftl");
		Writer out = new BufferedWriter(new FileWriter(new File("${config.generalProperties['output.dir']}/service-alphabetical.html")))
		temp.process(elements, out);
		out.flush();
	}
	
	def generateEntityIndex(def components,def config){
		def elements= [:]
		def registry = FileComponentRegistry.instance()
		
		elements['components']=components
		elements['registry']=registry
		elements['entities']=registry.alphabeticalEntities()
		elements['viewEntities']=registry.alphabeticalViewEntities()
		elements['extendEntities']=registry.alphabeticalExtendEntities()
		Template temp = cfg.getTemplate("entity-alphabetical.ftl");
		Writer out = new BufferedWriter(new FileWriter(new File("${config.generalProperties['output.dir']}/entity-alphabetical.html")))
		temp.process(elements, out);
		out.flush();
		
	}
	def generateModuleIndex(def components, def config){
		def elements= [:]
		elements['components']=components  		
		Template temp = cfg.getTemplate("module.ftl");
		Writer out = new BufferedWriter(new FileWriter(new File("${config.generalProperties['output.dir']}/module.html")))
		temp.process(elements, out);
		out.flush();
	}
	
	def generateDirectories(def component){
		def config = ConfigurationManager.instance()
		def siteDir = new File(config.getSiteDir(component))
		if(!siteDir.exists()){
			siteDir.mkdirs()
		}
		def imagesDir = new File(config.getImagesDir(component))
		if(!imagesDir.exists()){
			imagesDir.mkdirs()
		}
		return siteDir
	}
	
}

